package com.tuzhi.filestore.fileback;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson2.JSONObject;
import com.tuzhi.base.web.vo.Result;
import com.tuzhi.filestore.config.FileStoreConfig;
import com.tuzhi.filestore.http.BillApiClient;
import com.tuzhi.util.DateTzUtil;
import com.tuzhi.vo.bill.BackFileVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;


/**
 * 文件备份服务类
 * 排队系统系统客户提交的订单
 * 此功能先不上，测试系统反馈，订单的资源同样可以删除掉
 */
@Service
@Slf4j
public class FileBackupsV2ServiceImpl {
    final String format = "yyyyMMdd";
    //备份文件指定日期（30天前的）
    final static int day = 90;
    final static long day_ms = 24 * 60 * 60 * 1000;
    @Autowired
    FileStoreConfig fileStoreConfig;

    @Autowired
    BillApiClient billApiClient;


    /**
     * 加载今天之前  beforeTday 天的文件集合记录
     *
     * @param dir        数据源目录
     * @param beforeTday 指定的天数和
     * @param type       (1,客户上传的，2，软件角色的模型）
     * @param backFileVo 排除的测试系统的文件
     * @return
     */
    private List<File> loadFilesOfThenDay(String dir, int beforeTday, int type, BackFileVo backFileVo) {
        List<File> fileList = new ArrayList<>();
        File directory = new File(dir);
        File[] files = directory.listFiles();
        if (files == null || files.length == 0) {
            log.info("没有文件内容：{}，{}", dir, type);
            return fileList;
        }
        long sevenDaysAgo = new Date().getTime() - beforeTday * day_ms;

        for (File file : files) {
            String fileName = file.getName();
            if (file.isFile() && file.lastModified() < sevenDaysAgo) {
                if (backFileVo != null) {
                    if (type == 1) {
                        if (backFileVo.getFileNames() != null && backFileVo.getFileNames().contains(fileName)) {
                            log.info("测试系统的文件，不移走：{}", fileName);
                            continue;
                        }
                    } else if (type == 2) {
                        Set<Long> mids = backFileVo.getModuleIds();
                        if (mids != null) {
                            String moduleIdStr = fileName.substring(0, fileName.indexOf("."));
                            if (StringUtils.isNotEmpty(moduleIdStr)) {
                                if (mids.contains(Long.parseLong(moduleIdStr))) {
                                    log.info("测试系统的文件，不移走：{}", fileName);
                                    continue;
                                }
                            }
                        }
                    }
                }
                fileList.add(file);
            }
        }
        return fileList;
    }


    /**
     * 备份客户上传的模型文件
     */
    private void backupsFileOfUpModelFile(BackFileVo backFileVo) {
        Date curDate = new Date();
        Date srcDate = DateTzUtil.addDays(curDate, -1 * day);
        String srcDirName = DateUtil.format(srcDate, "yyyyMM");
        //待备份的目录
        String srcDir = Paths.get(fileStoreConfig.getSavePath(), srcDirName).toString();
        List<File> files = loadFilesOfThenDay(srcDir, day, 1, backFileVo);
        String dirName = DateUtil.format(new Date(), format);
        String backPathDir = Paths.get(fileStoreConfig.getSavePath(), "backupsModel", dirName).toString();
        //1.copy文件到指定的目录
        files.forEach(f -> {
            String paths = Paths.get(backPathDir, f.getName()).toString();
            File newFile = new File(paths);
            FileUtil.move(f, newFile, true);
        });
        log.info("{}:备份文件数量：{}", backPathDir, files.size());
    }


    private void backupsFile(BackFileVo backFileVo) {
        String dirName = DateUtil.format(new Date(), format);
        String backPathDir = Paths.get(fileStoreConfig.getSavePath(), "backups", dirName).toString();
        if (FileUtil.exist(backPathDir)) {
            log.info("目录己存在：不备份:{}", dirName);
            return;
        }
        //待备份的目录
        String srcDir = Paths.get(fileStoreConfig.getSavePath(), "tuovisual").toString();
        List<File> files = loadFilesOfThenDay(srcDir, day, 2, backFileVo);
        //1.copy文件到指定的目录
        files.forEach(f -> {
            String paths = Paths.get(backPathDir, f.getName()).toString();
            File newFile = new File(paths);
            FileUtil.move(f, newFile, true);
        });
        log.info("{}:备份文件数量：{}", backPathDir, files.size());
    }

    public void backFile() {
        Long org = fileStoreConfig.getOrg();
        org = org == null ? 1 : org;
        Result<BackFileVo> result = billApiClient.listTestFile(org);
        if (result != null && "0".equals(result.getCode())) {
            BackFileVo backFileVo = result.getData();
            backupsFileOfUpModelFile(backFileVo);
            backupsFile(backFileVo);
        } else {
            log.info("查找测试系统的单失败：{}不备份", JSONObject.toJSONString(result));
        }
    }

    public static void main(String[] args) {
        String f = "501266.3.bin";
        System.out.println(f.substring(0, f.indexOf(".")));
    }
}
